//
//  RSDBQuery.m
//  WWRU
//
//  Created by Johnnie Walker on 09/04/2009.
//  Copyright 2009 Random Sequence. All rights reserved.
//

#import "RSDBQuery.h"
#import "RSDB.h"
#import "RSDBTable.h"

@implementation RSDBQuery

@synthesize limit;
@synthesize offset;
@synthesize parameters;
@synthesize conditions;
@synthesize columns;
@synthesize table;
@synthesize orderby;

- (id) init
{
	self = [super init];
	if (self != nil) {
		self.columns = [NSArray array];
		self.parameters = [NSArray array];
		self.conditions = [NSArray array];	
		self.orderby = [NSArray array];			
	}
	return self;
}

- (void) dealloc
{
	self.columns = nil;
	self.parameters = nil;
	self.conditions = nil;	
	self.orderby = nil;				
	[super dealloc];
}


- (RSDBQuery *)addColumn:(id)columnName
{
	self.columns = [columns arrayByAddingObject:columnName];
	return self;
}

- (RSDBQuery *)addParameter:(id)parameter
{
	self.parameters = [parameters arrayByAddingObject:parameter];	
	return self;
}

- (RSDBQuery *)addCondition:(NSString *)condition
{
	self.conditions = [conditions arrayByAddingObject:condition];	
	return self;
}

- (RSDBQuery *)addCondition:(NSString *)condition parameter:(id)parameter
{
	[self addCondition:condition];
	[self addParameter:parameter];	
	return self;
}

- (RSDBQuery *)addOrderby:(NSString *)columnName;
{
	self.orderby = [orderby arrayByAddingObject:columnName];
	return self;
}

- (RSDBQuery *)addOrderby:(NSString *)columnName ascending:(BOOL)ascending;
{
	if (ascending) {
		return [self addOrderby:columnName];
	}
	
	[self addOrderby:[NSString stringWithFormat:@"%@ DESC",columnName]];
	return self;
}

- (NSArray *)execute
{
	NSString *offsetString = @"";
	if (offset > 0) {
		offsetString = [NSString stringWithFormat:@"OFFSET %i",offset];
	}	
	
	NSString *limitString = @"";
	if (limit > 0) {
		limitString = [NSString stringWithFormat:@"LIMIT %i",limit];
	}
		
	NSString *columnsString = @"*";
	if (columns.count > 0) {
		columnsString = [columns componentsJoinedByString:@","];
	}
	
	NSString *whereString = @"";
	if (conditions.count > 0) {
		whereString = [NSString stringWithFormat:@"WHERE %@",[conditions componentsJoinedByString:@" AND "]];	
	}	
	
	NSString *orderByString = @"";
	if (orderby.count > 0) {
		orderByString = [NSString stringWithFormat:@"ORDER BY %@",[orderby componentsJoinedByString:@", "]];	
	}
	
	NSString *sql = [NSString stringWithFormat:@"SELECT %@ FROM <tablename> %@ %@ %@%@",columnsString,whereString,orderByString,limitString,offsetString];
	
//#ifdef DEBUG_BUILD
//	NSLog(@"query sql: %@ parameters: %@",sql,parameters);
//#endif
	
	return [table findBySQL:sql arguments:parameters];
}

- (RSDBRecord *)findOne 
{
	self.limit = 1;
	NSArray *results = [self execute];
	if (results.count < 1) {
		return nil;			
	}
	return [results objectAtIndex:0];
}

@end





